package com.njtoyo.taxi.admin.service.business.impl;


import cn.hutool.core.lang.Dict;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njtoyo.taxi.admin.mapper.master.entity.DriverRegionTaxiStartingPrice;
import com.njtoyo.taxi.admin.mapper.master.entity.StartPrice;
import com.njtoyo.taxi.admin.mapper.master.mapper.DriverRegionTaxiStartingPriceMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.StartPriceMapper;
import com.njtoyo.taxi.admin.rest.presenter.business.operation_rule.start_price.StartPricePagePresenter;
import com.njtoyo.taxi.admin.rest.wrapper.business.operation_rule.start_price.StartPriceAddUpdateWrapper;
import com.njtoyo.taxi.admin.service.business.StartPriceService;
import com.taxi.entity.common.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StartPriceServiceImpl extends ServiceImpl<StartPriceMapper, StartPrice> implements StartPriceService {

    @Autowired
    private DriverRegionTaxiStartingPriceMapper driverRegionTaxiStartingPriceMapper;

    @Override
    public RestResult list(Integer current, Integer size, String regionId) {
        Page<StartPricePagePresenter> page = new Page<>(current, size);
        IPage<StartPricePagePresenter> pages = baseMapper.getListPage(page, regionId);
        return RestResult.success(pages);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RestResult add(StartPriceAddUpdateWrapper wrapper) {
        Boolean isExist = checkExist(wrapper.getDriverRegionId(), wrapper.getId());
        if (isExist) {
            return RestResult.failed("该运营区域内已存在起步价规则，请勿重复添加");
        }
        Dict period = Dict.create().set("start", "00:00:00").set("end", "23:59:59");
        Dict starting_price = Dict.create().set("mileage", wrapper.getMileage()).set("price", wrapper.getPrice());
        Dict jsonObj = Dict.create()
                .set("period", period)
                .set("starting_price", starting_price)
                .set("normal_unit_price", wrapper.getNormalUnitPrice());
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(jsonObj);
        String rule = JSONUtil.toJsonStr(jsonArray);
        StartPrice startPrice = new StartPrice();
        startPrice.setTitle(wrapper.getTitle());
        startPrice.setRule(rule);
        baseMapper.insert(startPrice);

        //绑定运营区
        driverRegionTaxiStartingPriceMapper.insert(new DriverRegionTaxiStartingPrice()
                .setDriverRegionId(Long.parseLong(wrapper.getDriverRegionId()))
                .setRuleId(startPrice.getId()));
        return RestResult.success();
    }

    private Boolean checkExist(String driverRegionId, Long id) {
        if (id == null) {
            if (driverRegionTaxiStartingPriceMapper.selectCount(new QueryWrapper<DriverRegionTaxiStartingPrice>()
                    .eq("driver_region_id", driverRegionId)) > 0) {
                return true;
            }
        } else {
            if (driverRegionTaxiStartingPriceMapper.selectCount(new QueryWrapper<DriverRegionTaxiStartingPrice>()
                    .eq("driver_region_id", driverRegionId)
                    .ne("rule_id", id)) > 0) {
                return true;
            }
        }
        return false;
    }

    @Override
    public RestResult getInfo(Long id) {
        StartPricePagePresenter presenter = baseMapper.getInfoById(id);
        return RestResult.success(presenter);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult update(StartPriceAddUpdateWrapper wrapper) {
        Boolean isExist = checkExist(wrapper.getDriverRegionId(), wrapper.getId());
        if (isExist) {
            return RestResult.failed("该运营区域内已存在起步价规则，请勿重复添加");
        }
        Dict period = Dict.create().set("start", "00:00:00").set("end", "23:59:59");
        Dict starting_price = Dict.create().set("mileage", wrapper.getMileage()).set("price", wrapper.getPrice());
        Dict jsonObj = Dict.create()
                .set("period", period)
                .set("starting_price", starting_price)
                .set("normal_unit_price", wrapper.getNormalUnitPrice());
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(jsonObj);
        String rule = JSONUtil.toJsonStr(jsonArray);
        StartPrice startPrice = new StartPrice();
        startPrice.setTitle(wrapper.getTitle());
        startPrice.setRule(rule);
        startPrice.setId(wrapper.getId());
        baseMapper.updateById(startPrice);

        driverRegionTaxiStartingPriceMapper.delete(new QueryWrapper<DriverRegionTaxiStartingPrice>()
                .eq("rule_id", wrapper.getId()));
        driverRegionTaxiStartingPriceMapper.insert(new DriverRegionTaxiStartingPrice()
                .setDriverRegionId(Long.parseLong(wrapper.getDriverRegionId()))
                .setRuleId(wrapper.getId()));
        return RestResult.success();
    }
}
